package com.app.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.app.common.SystemConstant;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.GoodsSpecsService;
import com.app.service.IDividedIntoRecordService;
import com.app.service.InviteConfigService;
import com.app.utils.AliyunOSSUtils;
import com.app.utils.CommonHelp;
import com.app.vo.GoodsSpecsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import static com.app.common.SystemConstant.DEFAULT_PDF_SERVICE_URL;


/**
 * 商品规格
 *
 * @author 16693103420
 * @since 2024-01-25
 */
@Service
public class GoodsSpecsServiceImpl extends ServiceImpl<GoodsSpecsMapper, GoodsSpecsModel> implements GoodsSpecsService {
    @Autowired
    private GoodsSpecsMapper goodsSpecsMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IntegralOrderMapper integralOrderMapper;
    @Autowired
    private IntegralRecordMapper integralRecordMapper;
    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private MessageBoxMapper messageBoxMapper;

    @Autowired
    private InviteConfigService inviteConfigService;

    //商品规格信息查询
    @Override
    public GoodsSpecsVo getGoodsSpecsList(Integer page, Integer limit, Integer goodsId) {
        Page<GoodsSpecsModel> page1 = new Page<>(page, limit);

        QueryWrapper<GoodsSpecsModel> qw = new QueryWrapper<>();
        if (goodsId != null && goodsId != 0) {
            qw.eq("goods_id", goodsId);
        }
        qw.orderByDesc("create_time");
        Page<GoodsSpecsModel> goodsSpecsPage = goodsSpecsMapper.selectPage(page1, qw);
        List<GoodsSpecsModel> goodsSpecsList = goodsSpecsPage.getRecords();

        long count = goodsSpecsPage.getTotal();
        GoodsSpecsVo goodsSpecsVo = new GoodsSpecsVo();
        goodsSpecsVo.setList(goodsSpecsList);
        goodsSpecsVo.setCount((int) count);
        return goodsSpecsVo;
    }

    @Autowired
    private AliyunOSSUtils aliyunOSSUtils;
    @Autowired
    private IDividedIntoRecordService dividedIntoRecordService;
    @Autowired
    private InviteConfigMapper inviteConfigMapper;

    //立即兑换
    @Override
    public String exchangeGoods(GoodsSpecsModel goodsSpecsModel, Integer userId) {
        //将用户积分益联券扣掉
        GoodsModel goodsModel = goodsMapper.selectById(goodsSpecsModel.getGoodsId());
        UserModel userModel = userMapper.selectById(userId);
        Double userVoucher = userModel.getVoucher();
        Double userIntegral = userModel.getIntegral();
        Double voucher = goodsModel.getVoucher() * goodsSpecsModel.getNumber();
        Double integral = goodsModel.getIntegral() * goodsSpecsModel.getNumber();
        if (userIntegral < integral || userVoucher < voucher) {
            return "用户益联券或积分不足";
        }
        //将商品库存信息数量减掉
        if (goodsModel.getNumber() >= goodsSpecsModel.getNumber()) {
            goodsModel.setNumber(goodsModel.getNumber() - goodsSpecsModel.getNumber());
            goodsMapper.updateById(goodsModel);
        } else {
            return "库存不足，无法兑换";
        }

        InviteConfigModel configModel = this.inviteConfigService.getById(1);

        Integer number = 1;
        if (goodsSpecsModel.getNumber() != null) {
            number = goodsSpecsModel.getNumber();
        }
        //生成积分商品订单
        IntegralOrderModel integralOrderModel = new IntegralOrderModel();
        //订单积分*数量
        integralOrderModel.setIntegral(goodsModel.getIntegral() * number);
        integralOrderModel.setVoucher(goodsModel.getVoucher() * number);
        integralOrderModel.setGoodsName(goodsModel.getName());
        integralOrderModel.setGoodsFace(goodsModel.getGoodsFace());
        integralOrderModel.setNumber(goodsSpecsModel.getNumber());
        integralOrderModel.setAddressId(goodsSpecsModel.getAddressId());
        integralOrderModel.setGoodsDetails(goodsModel.getLabel());
        integralOrderModel.setOrderSn(IdUtil.fastSimpleUUID());
        integralOrderModel.setUserId(userId);
        integralOrderModel.setAreaId(userModel.getAreaId());
        integralOrderModel.setCityId(userModel.getCityId());
        integralOrderModel.setGoodsId(goodsModel.getId());
        integralOrderModel.setCreateTime(CommonHelp.getNowTimestamp());
        integralOrderModel.setGoodsType(1);
        if (goodsModel.getApplyType() == 2) {
            integralOrderModel.setGoodsType(2);
            String code = IdUtil.fastSimpleUUID();
            // 生成二维码图片
            String verificationCodePath = System.getProperty("user.dir") + File.separator + "file" + File.separator + code + ".png";
            QrCodeUtil.generate("goods=2#" + code, 300, 300, FileUtil.file(verificationCodePath));
            String fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + code + ".png";
            try {
                aliyunOSSUtils.objectStorageUploadFile(fileURL, FileUtil.getInputStream(verificationCodePath));
            } catch (Exception e) {

            }
            integralOrderModel.setCodeUrl(fileURL);
            integralOrderModel.setCode(code);
            integralOrderModel.setBusinessId(goodsModel.getBusinessId());
            integralOrderModel.setBusinessUserid(goodsModel.getBusinessUserid());
            integralOrderModel.setStatus(7);
        }

        integralOrderMapper.insert(integralOrderModel);
        String orderId = integralOrderModel.getOrderSn();

//        //参与分成的券
//        Double dividedIntoCoupons = voucher * configModel.getTransactionFeeRatio();
//        this.dividedIntoRecordService.dividingByRegionalAgent(userModel, BigDecimal.valueOf(dividedIntoCoupons), orderId, 3);
        //券
//        Double vouchersShouldGet = (BigDecimal.valueOf(voucher).subtract(BigDecimal.valueOf(dividedIntoCoupons)).doubleValue());

//        vouchersShouldGet=0d;

        userIntegral = userIntegral - integral;
        userVoucher = userVoucher - voucher;
        userModel.setIntegral(userIntegral);
        userModel.setVoucher(userVoucher);
        userMapper.updateById(userModel);


        //生成用户积分使用记录
        IntegralRecordModel integralRecordModel = new IntegralRecordModel();
        integralRecordModel.setName("积分商城");
        integralRecordModel.setTypeName("兑换");
        integralRecordModel.setContent(goodsModel.getName() + "*" + goodsSpecsModel.getNumber());
        String amountIntegral = String.format("-%.2f分", integral);
        integralRecordModel.setIntegral(amountIntegral);
        integralRecordModel.setUserId(userId);
        integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
        integralRecordModel.setOrderId(orderId);
        integralRecordModel.setVoucherType(0);
        integralRecordModel.setVoucherAmount(-integral);
        integralRecordMapper.insert(integralRecordModel);
        //生成用户益联券使用记录

        List<InviteConfigModel> inviteConfigModels = inviteConfigMapper.selectList(null);
        //手续费比例
        Double transactionFeeRatio = inviteConfigModels.get(0).getTransactionFeeRatio();
        //手续费
        double handlingFees = voucher * transactionFeeRatio;

        VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
        voucherRecordModel.setName("积分商城");
        voucherRecordModel.setTypeName("线下兑换商品");
        voucherRecordModel.setContent(goodsModel.getName() + "*" + goodsSpecsModel.getNumber());
        String amountVoucher = "-" + voucher + "券";
        voucherRecordModel.setVoucher(amountVoucher);
        voucherRecordModel.setUserId(userId);
        voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
        voucherRecordModel.setOrderId(orderId);
        voucherRecordModel.setVoucherType(0);
        voucherRecordModel.setWriteOff(2);
        voucherRecordModel.setVoucherAmount(-voucher);
        voucherRecordModel.setFees(BigDecimal.valueOf(handlingFees).setScale(2, RoundingMode.HALF_UP));
        voucherRecordMapper.insert(voucherRecordModel);
        //消息盒子记录数据
        MessageBoxModel messageBoxModel = new MessageBoxModel();
        messageBoxModel.setUserId(userModel.getId());
        messageBoxModel.setQuiltUserId(userModel.getId());
        messageBoxModel.setTypeName("兑换商品成功通知");
        messageBoxModel.setVoucher(voucher);
        messageBoxModel.setNotes("兑换商品");
        messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
        messageBoxModel.setOrderSn(orderId);
        messageBoxMapper.insert(messageBoxModel);
        return "兑换成功";
    }
}
